#include "setclient.h"
#include <QtWidgets>
#include <QHostAddress>
#include "servernetworkprocessing.h"
SetClient::SetClient(QWidget *parent)
    : QDialog(parent),
      s_EC(ExperimentConfiguration::get())
{

    QGroupBox *inputWidgetBox = createInputWidgets();
    QDialogButtonBox *buttonBox = createButtons();

    QVBoxLayout *layout = new QVBoxLayout;
    layout->addWidget(inputWidgetBox);
    layout->addWidget(buttonBox);
    setLayout(layout);

    setWindowTitle(tr("新增客户机"));
}
QGroupBox * SetClient::createInputWidgets()
{
    QGroupBox *box = new QGroupBox();
    QLabel *ipAddrLabel = new QLabel(tr("客户机IP地址:"));
    ipAddrEditor = new QLineEdit;

    QGridLayout *layout = new QGridLayout;
    layout->addWidget(ipAddrLabel, 0, 0);
    layout->addWidget(ipAddrEditor, 0, 1);
    box->setLayout(layout);

    return box;
}
QDialogButtonBox * SetClient::createButtons()
{
    QPushButton *closeButton = new QPushButton(tr("关闭"));
    QPushButton *submitButton = new QPushButton(tr("保存"));

    closeButton->setDefault(true);

    connect(closeButton, &QPushButton::clicked, this, &SetClient::close);
    connect(submitButton, &QPushButton::clicked, this, &SetClient::submit);

    QDialogButtonBox *buttonBox = new QDialogButtonBox;
    buttonBox->addButton(submitButton, QDialogButtonBox::ResetRole);
    buttonBox->addButton(closeButton, QDialogButtonBox::RejectRole);

    return buttonBox;
}
void SetClient::submit()
{
    QString ipAddr = ipAddrEditor->text();
    QHostAddress address; // 借助QHostAddress判断输入的内容的格式是不是IP

    bool isAddr= address.setAddress(ipAddr.trimmed()); // timmed是去掉空格

    if (!isAddr){
        QString message(tr("请输入正确的客户机地址"));
        QMessageBox::information(this, tr("新增客户机"), message);
    } else {

        ClientInformation *addClientInformation = new ClientInformation;
        s_EC.clientInfor = addClientInformation;
        s_EC.clientIp = ipAddr;
        s_EC.tcpServer = new ServerNetworkProcessing;
        //s_EC.clientIpList.push_back(ipAddr);
        accept();
    }
}
